<?php

namespace App\Http\Controllers\Home;

use App\Model\UserSearchRecords;
use App\Model\WeChatFromId;
use App\Model\WineProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SearchController extends BaseController
{
    private $query;
    /*
     * 产品类别 wine_product.category
     * 产区：国家+大区 +子产区（例：法国、波尔多、梅多克）sys_country,sys_g_regions,sys_subdivision
     * 生产年份  wine_product.vintage
     * 消费场景  wine_product_scene.name
     * 菜系     wine_cuisines.name
     * 产品档次  wine_gradings.name
     * 品种     wine_product_deployment.name
     * 产品风格  wine_tastes.name
     */

    public function search(Request $request)
    {
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        $keyword = $request->input('keyword');
        $pageSize = 10;

        $ids = UserSearchRecords::getSearchResult($keyword);

        if (!$ids) $ids = $this->getProductIds($keyword);

        $ids = $this->getProductIds($keyword);

        //保存搜索结果
        UserSearchRecords::saveRecord($this->loginUserId(),$keyword,json_encode($ids));

        $items = WineProduct::whereIn('id',$ids)->where('online','=',"yes")
            ->orderBy('weight','desc')
            ->orderBy('created_at','desc')
            ->with(['userWantDrink','sku'])
            ->select('id','name','chname','banner','order_count')
            ->paginate($pageSize);

        return $this->success($items);
    }

    public function getProductIds($keyword)
    {
        //DB::enableQueryLog();

        $row[1] = $this->processName($keyword);
        $row[2] = $this->processCategory($keyword);

        $ids = [];
        foreach ($row as $v){
            $ids = array_merge($ids,$v->toArray());
        }

        $ids = array_unique($ids);

        //$ids = array_slice($ids,$pageSize*($page-1),$pageSize);

        //dd($ids,DB::getQueryLog());

        return $ids;
    }

    //1.产品名称
    public function processName($keyword)
    {
        return DB::table('wine_product')->whereNull('deleted_at')->whereRaw('`name` like ? or `chname` like ?',
            ["%".$keyword."%","%".$keyword."%"])->pluck('id');
    }

    //2.产品类别
    public function processCategory($keyword)
    {
        return DB::table('product_category_relations')->whereNull('deleted_at')->whereRaw('category_id in (select id from 
        product_categories where deleted_at is null and name like ?)',["%".$keyword."%"])->pluck('product_id');
    }
}
